package bin_tree.leetcode;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author shkstart
 * 二叉树的层序遍历
 * @create 2022-10-18-16:44
 */
public class Num102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
//            保存每层元素的个数
            List<Integer> level = new LinkedList<>();
            //队列中保存每一层的节点
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                level.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }

            }
            ret.add(level);
        }
        return ret;

    }
}
